﻿package crochet.core;

/*
 Copyright 2011 Intuitive Solutions

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

import crochet.core.policy.DefaultExecutionPolicy;
import crochet.core.policy.IExecutionPolicy;

public class ThreadScheduler implements IScheduler, Runnable {
	protected Thread tThread;
	protected boolean bIterate;
	protected Object areAutoResetEvent;
	protected IProcessDoneDelegate ProcessDoneEvent;
	protected IExecutionPolicy epExecutionPolicy, epCloneableExecutionPolicy;

	public ThreadScheduler() {
		this(new DefaultExecutionPolicy(null, null, null));
	}

	public ThreadScheduler(IExecutionPolicy epCloneableExecutionPolicy) {
		bIterate = true;
		areAutoResetEvent = new Object();
		this.epCloneableExecutionPolicy = epCloneableExecutionPolicy;
		tThread = new Thread(this);

		if (epCloneableExecutionPolicy.getRootScheduler() == null) {
			epCloneableExecutionPolicy.setRootScheduler(this);
		}

		tThread.start();
	}

	public IExecutionPolicy getCloneableExecutionPolicy() {
		return epCloneableExecutionPolicy;
	}

	public void schedule(IExecutionPolicy epExecutionPolicy) {
		this.epExecutionPolicy = epExecutionPolicy;

		synchronized (areAutoResetEvent) {
			areAutoResetEvent.notify();
		}
	}

	public void schedule(ISchedulerDelegate sdSchedulerDelegate) {
		schedule(sdSchedulerDelegate, null);
	}

	public void schedule(ISchedulerDelegate sdSchedulerDelegate,
			IExceptionHandlerDelegate ehdExceptionHandlerDelegate) {
		schedule(epCloneableExecutionPolicy.clone(sdSchedulerDelegate,
				ehdExceptionHandlerDelegate));
	}

	public void run() {
		while (bIterate) {
			try {
				synchronized (areAutoResetEvent) {
					areAutoResetEvent.wait();
				}

				if (bIterate) {
					epExecutionPolicy.execute(this);

					ProcessDoneEvent.handleDone(this);
				}
			} catch (Exception e) {
			}
		}
	}

	public void setProcessDoneEvent(IProcessDoneDelegate ProcessDoneEvent) {
		this.ProcessDoneEvent = ProcessDoneEvent;
	}

	public void dispose() {
		bIterate = false;
		synchronized (areAutoResetEvent) {
			areAutoResetEvent.notify();
		}

		try {
			tThread.join(10000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}